package com.wang.sse.controller;

import com.wang.sse.service.SseEmitterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * @author: wangning1@abupdate.com
 * @date: 2023-12-14 09:45
 **/
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/sse")
public class SseEmitterController {

    @Autowired
    private SseEmitterService sseEmitterService;

    /**
     * 创建SSE连接
     *
     * @return
     */
    @GetMapping("/connect/{id}")
    public SseEmitter connect(@PathVariable("id") String id) {
        return sseEmitterService.connect(id);
    }

    /**
     * 单播
     *
     * @param id
     * @param message
     */
    @PostMapping("/publisher/{id}")
    public void publisher(@PathVariable("id") String id,
                          @RequestParam String message){
        sseEmitterService.publisher(id, message);
    }

    /**
     * 广播消息
     *
     * @param message
     */
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestParam String message) {
        sseEmitterService.sendMessage(message);
    }

}